package com.party.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.common.constant.strings.AliyunServiceMsg;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * created with IntelliJ IDEA
 *
 * @author W
 * @date 2021/07/16/9:06
 * Other:对象存储控制层
 */
@RestController
@RequestMapping("/oss")
@CrossOrigin
public class OssController {
    /**
     * 图片上传接口
     *
     * @param file 文件
     * @return {@link String}
     * @throws IOException ioexception
     */
    @PostMapping("/policy")
    public String uploadFile(@RequestBody MultipartFile file) throws IOException {

        OSSClient ossClient = new OSSClient(AliyunServiceMsg.ALIYUN_OSS_ENDPOINT, AliyunServiceMsg.ALIYUN_OSS_ACCESS_KEY, AliyunServiceMsg.ALIYUN_OSS_SECRET_KEY);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 最后上传生成的文件名
        String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
        // oss中的文件夹名
        String objectName = sdf.format(new Date()) + "/" + finalFileName;
        // 创建上传文件的元信息，可以通过文件元信息设置HTTP header(设置了才能通过返回的链接直接访问)。
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(AliyunServiceMsg.ALIYUN_OSS_CONTENT_TYPE);
        // 文件上传
        ossClient.putObject(AliyunServiceMsg.ALIYUN_OSS_BUCKET, objectName, new ByteArrayInputStream(file.getBytes()),objectMetadata);
        // 设置URL过期时间为1小时。
        Date expiration = new Date(System.currentTimeMillis() + 360000 * 1000);
        ossClient.generatePresignedUrl(AliyunServiceMsg.ALIYUN_OSS_BUCKET, objectName, expiration);
        ossClient.shutdown();
        System.out.println(AliyunServiceMsg.ALIYUN_OSS_URL+objectName);
        return AliyunServiceMsg.ALIYUN_OSS_URL+objectName;
    }

}
